package tsvetanv.inventory.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import tsvetanv.inventory.model.Article;
import tsvetanv.inventory.util.dao.CustomHibernateDaoSupport;

/**
 * The <code>ArticleDaoImpl</code> class implements the actions with database
 * related with {@link Article} class.
 * 
 * @author Tsvetan Vasilev
 * 
 */
@Repository("articleDao")
public class ArticleDaoImpl extends CustomHibernateDaoSupport implements
		ArticleDao {

	public void save(Article article) {
		getHibernateTemplate().save(article);

	}

	public void update(Article article) {
		getHibernateTemplate().update(article);

	}

	public void delete(Article article) {
		// make object persistent
		Article persistedArticle = findByArticleId(article.getId());

		getHibernateTemplate().delete(persistedArticle);

	}

	@SuppressWarnings("unchecked")
	public Article findByArticleId(int articleId) {
		List<Article> articles = getHibernateTemplate().find(
				"from Article where id=?", articleId);
		return (articles == null || articles.isEmpty()) ? null : articles
				.get(0);
	}

	@SuppressWarnings("unchecked")
	public Article findByProductName(String productName) {
		List<Article> articles = getHibernateTemplate().find(
				"from Article where product.name=?", productName);
		return (articles == null || articles.isEmpty()) ? null : articles
				.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<Article> getAllArticles() {
		return getHibernateTemplate().find("from Article");
	}

}
